<template>
  <CDialog
    title="设置碳排放因子"
    :close-on-click-modal="false"
    v-model:visible="dialogVisible"
    :footer="false"
  >
    <div class="g-mb20" v-loading="loading">
      <CTable
        ref="tableRef"
        useDataSource
        :dataSource="dataSource"
        border
        :pagination="false"
        :tableFieldsSetting="tableFieldsSetting"
      >
        <template #factorCoefficientSlot="{ scope }">
          {{ empty(scope.row.factorCoefficient) }} {{ empty(scope.row.factorUnit) }}
        </template>
        <template #opSlot="{ scope }">
          <el-button
            text
            type="primary"
            @click="handleChangeFactor(scope.row)"
            :loading="scope.row.loading ?? false"
            v-btnPermission="'TAA_EDIT_FACTOR'"
            >更换因子</el-button
          >
        </template>
      </CTable>
    </div>
    <CFactorDialog
      v-model:visible="factorDialogVisible"
      :taskForm="tempOpts"
      :selectRow="tempRow"
      @finish="handleFinish"
    />
  </CDialog>
</template>
<script lang="ts" setup name="CSetEmissionFactorDialog">
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CTable, TableFieldsSettingType } from '@/components/CTable';
import { useMessage } from '@/hooks/useMessage';
import CFactorDialog from '@/businessComponents/CFactorDialog/index.vue';
import { getListRelation, postUpdateRelation } from '@/apis/taa/target/target';
import type { GetListRelationResult } from '@/apis/taa/target/model/targetModel';
import _cloneDeep from 'lodash/cloneDeep';
import { empty } from '@/utils';

interface CSetEmissionFactorDialogProps {
  visible: boolean;
  loading?: boolean;
}
const props = withDefaults(defineProps<CSetEmissionFactorDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});
watch(
  () => props.visible,
  val => {
    if (val) {
      init();
    }
  }
);
const dataSource = ref<GetListRelationResult[]>();
const loading = ref(false);
const tableRef = ref();
async function init() {
  try {
    loading.value = true;
    dataSource.value = await getListRelation();
    loading.value = false;
  } catch (error) {
    console.log('error', error);
  }
}

const tableFieldsSetting: TableFieldsSettingType[] = [
  {
    title: '能源类型',
    field: 'materialName',
    minWidth: 100
  },
  {
    title: '单位',
    field: 'materialUnit',
    minWidth: 80
  },
  {
    title: '因子名称',
    field: 'factorName',
    minWidth: 150
  },
  {
    title: '因子值',
    field: 'factorCoefficient',
    slot: 'factorCoefficientSlot',
    minWidth: 150
  },
  {
    title: '操作',
    field: 'op',
    slot: 'opSlot',
    align: 'center',
    minWidth: 100,
    fixed: 'right'
  }
];

const factorDialogVisible = ref(false);
const tempRow = ref<GetListRelationResult>();
const tempOpts = reactive({
  materialName: '',
  dataUnit: ''
});

/**
 * 更换因子
 */
function handleChangeFactor(row: GetListRelationResult) {
  console.log('handleChangeFactor', row);
  factorDialogVisible.value = true;
  tempRow.value = _cloneDeep(row);
  tempOpts.materialName = row.materialName;
  tempOpts.dataUnit = row.materialUnit;
}

async function handleFinish(row: GetListRelationResult) {
  console.log('handleFinish', row);
  if (!tempRow.value) {
    createMessage.error('异常错误，请刷新重试！');
    return;
  }
  try {
    const params = {
      relationNo: row.relationNo,
      factorNo: row.factorNo,
      factorName: row.factorName,
      factorUnit: row.factorUnit
    };
    tableRef.value?.showLoading();
    await postUpdateRelation(params);
    tableRef.value?.hideLoading();
    createMessage.success('更换成功！');
    init();
    emits('refresh');
  } catch (error) {
    console.log('error', error);
    tableRef.value?.hideLoading();
  }
}
</script>
<style lang="scss" scoped></style>
